import {
  getApprovalRecord,
  // getReadRecord,
  getApprovalButton,
  getReturnPerson,
  getPartyRelationTree,
  // getApprovalExecute,
  // getReadMsgBatchAdd,
  // getUpdataRead,
  postExecuteAgree,
  postExecuteDisagree,
  postExecuteReturn,
  postExecuteTransfer,
  postExecuteAssist,
} from "@/basa/api/template-request";
export const mixinCommon = {
  data() {
    return {
      // 面包屑相关数据
      // name: "",
      mainTypeName: "",
      // 审批状态icon的样式
      approving: "",
      approvingStatus: true,
      approvingType: {
        2: "approving", // 审批中
        3: "approvaled", // 审批通过
        4: "sendback", // 已退回
        5: "unapproval", // 审批不通过
        6: "withdrawn", // 已撤回
      },
      // gepma使用这个
      approvingType1: {
        2: "approving", // 审批中
        3: "withdrawn", // 已撤回
        4: "approvaled", // 审批通过
        5: "sendback", // 审批退回
        6: "unapproval", // 审批不通过
      },
      //分包用这个
      approvingType2: {
        1: "approving", // 审批中
        2: "withdrawn", // 已撤回
        3: "approvaled", // 审批通过
        4: "sendback", // 审批退回
        5: "unapproval", // 审批不通过
      },
      // smp使用这个
      smpApprovingType: {
        1: "approving", // 审批中
        2: "withdrawn", // 已撤回
        3: "approvaled", // 审批通过
        4: "sendback", // 审批退回
        5: "unapproval", // 审批不通过
      },
      approvingType5: {
        "1": "approving", // 审批中
        "2": "withdrawn", // 已撤回
        "3": "approvaled", // 审批通过
        "4": "sendback", // 审批退回
        "5": "unapproval", // 审批不通过
      },
      // 阅读记录数据
      tableDataRead: [],
      // 审批记录数据
      activities: [],
      // 编辑
      dialogEdit: false,
      iframeSrc: "", // 接收编辑按钮反的地址
      // 同意,不同意
      dialogAgree: false,
      dialogAgreeType: "",
      dialogAgreeValue: "",
      // 退回
      dialogReturn: false,
      dialogReturnValue: "退回",
      dialogReturnTags: [],
      dialogReturnPerson: [],
      // 转审,协办
      dialogTransfer: false,
      dialogTransferType: "transfer",
      dialogTransferValue: "",
      dialogTransferTags: [],
      dialogTag: [],
      dialogTransferReset: true,
      tagCon: "", // 知会拼接多个name
      expandedKeys: [], // default tree
      dataKeys: [],
      autoCode: "", // 接收按钮接口返回的人员部门信息
      isMultiWorkItem: "",
      dialogTransferDefaultProps: {
        label: "name",
        isLeaf: "isLeaf",
      },
      // 底部功能按钮相关
      approvalButtons: [
        // {
        //   type: "btnEdit",
        //   text: "编辑",
        //   icon: "icon-ccui-edit",
        //   click: () => {
        //     this.commonLock === false && this.dialogEditClick();
        //   }
        // },
        {
          type: "btnAgree",
          text: "同意",
          icon: "icon-ccui-agree",
          click: () => {
            this.commonLock === false && this.dialogAgreeClick("agree");
          },
        },
        // {
        //   type: "btnResubmit",
        //   text: "提交",
        //   icon: "icon-ccui-agree",
        //   click: () => {
        //     this.commonLock === false && this.dialogAgreeClick("resubmit");
        //   }
        // },
        {
          type: "btnDisAgree",
          text: "不同意",
          icon: "icon-ccui-disagree",
          click: () => {
            this.commonLock === false && this.dialogAgreeClick("disAgree");
          },
          noShow: true,
        },
        {
          type: "btnBack",
          text: "退回",
          icon: "icon-ccui-reject",
          click: () => {
            this.commonLock === false && this.dialogReturnClick();
          },
        },
        {
          type: "btnTransfer",
          text: "转审",
          icon: "icon-ccui-transfer",
          click: () => {
            this.commonLock === false && this.dialogTransferClick("transfer");
          },
        },
        {
          type: "btnAssist",
          text: "协办",
          icon: "icon-ccui-jointly",
          click: () => {
            this.commonLock === false && this.dialogTransferClick("assist");
          },
        },
        // {
        //   type: "btnTell",
        //   text: "知会",
        //   icon: "icon-ccui-notify",
        //   click: () => {
        //     this.commonLock === false && this.dialogTransferClick("notify");
        //   }
        // }
      ],
      approvalButtonAuth: {},
      isRepeatedly: false,
      commonLock: false, // 底部按钮遮罩层
      dialogEditHack: false,
      options: [
        { label: "申请人", value: "1" },
        { label: "上一环节审批人", value: "2" },
      ],
      selectTypeCode: "1",
    };
  },
  computed: {
    // 获取地址栏面包屑数据
    breadcrumbObj() {
      return Object.keys(this.$store.getters.getBreadcrumb).length > 0
        ? this.$store.getters.getBreadcrumb
        : JSON.parse(sessionStorage.getItem("getBreadcrumb"));
    },
    // 获取业务数据所需入参
    businessParams() {
      return Object.keys(this.$store.getters.businessList).length > 0
        ? this.$store.getters.businessList
        : JSON.parse(sessionStorage.getItem("businessList"));
    },
    isShowDivider() {
      let newApprovalButtonAuth = JSON.parse(
        JSON.stringify(this.approvalButtonAuth)
      );
      delete newApprovalButtonAuth.bizState;
      delete newApprovalButtonAuth.currentOperUserAutoCode;
      delete newApprovalButtonAuth.isMultiWorkItem;
      let isShow = Object.values(newApprovalButtonAuth).every((item) => {
        return item === "0";
      });
      return isShow;
    },
    orgId() {
      return JSON.parse(localStorage.getItem("userInfo")).orgId;
    },
  },
  mounted() { },
  methods: {
    getRequestType() {
      if (
        (this.businessParams.srcType && this.businessParams.openType) ===
        undefined
      ) {
        return 0;
      } else {
        return this.businessParams.srcType === 0
          ? this.businessParams.openType === 1
            ? 1
            : 0
          : 1;
      }
    },
    // 审批记录
    getApprovalRecord() {
      const obj = {
        businessBillId: this.businessParams.businessBillId,
        businessCode: this.businessParams.businessCode,
        businessBillType: this.businessParams.businessBillType,
        businessAppId: this.businessParams.appId,
        businessOrgId: this.orgId,
        currentOperUserId: this.businessParams.currentOperUserId,
        requestType: this.getRequestType(),
        isDelete: 0,
      };
      getApprovalRecord(obj).then((res) => {
        res.data.data.recordList.forEach((item) => {
          if (item.operState === 0) {
            item.icon = "el-icon-time";
            item.color = "#F5A623";
          }
        });
        this.activities = res.data.data.recordList;
        this.activities.forEach((i) => {
          if (i.operatorStatusCode != 0) {
            i.operatorStatusName = i.operatorStatusName.replace(
              "点击此处",
              '<a @click="clickIt" style="color: #018AEF">点击此处</a>'
            );
          }
        });
      });
    },
    // 阅读记录
    // getReadRecord() {
    //   const obj = {
    //     businessBillId: this.businessParams.businessBillId,
    //     businessCode: this.businessParams.businessCode,
    //     businessBillType: this.businessParams.businessBillType,
    //     businessAppId: this.businessParams.appId,
    //     businessOrgId: this.orgId,
    //     currentOperUserId: this.businessParams.currentOperUserId,
    //     requestType: this.getRequestType()
    //   };
    //   getReadRecord(obj).then(res => {
    //     this.tableDataRead = res.data.data;
    //   });
    // },
    // 查询审批按钮
    getApprovalButton() {
      const obj = {
        todoId: this.businessParams.todoId,
        businessAppId: this.businessParams.businessAppId,
        businessBillId: this.businessParams.businessBillId,
        businessCode: this.businessParams.businessCode,
        businessBillTypeCode: this.businessParams.businessBillTypeCode,
        procInstId: this.businessParams.procInstId,
        actInstId: this.businessParams.actInstId,
        actInstName: this.businessParams.actInstName,
        workItemId: this.businessParams.workItemId,
        workItemStatus: this.businessParams.workItemStatus,
        currentOperUserId: this.businessParams.currentOperUserId,
        currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
      };
      getApprovalButton(obj).then((res) => {
        if (res.data.code === "0") {
          this.approvalButtonAuth = res.data.data || {};
          // delete this.approvalButtonAuth.btnTell;
          this.iframeSrc = res.data.data.btnEdit.editUrl || "";
          this.autoCode = res.data.data.currentOperUserAutoCode;
          this.isMultiWorkItem = res.data.data.isMultiWorkItem;
          if (
            this.approvalButtonAuth.bizState == 3 &&
            this.approvalButtonAuth.btnDisAgree == "1"
          ) {
            this.approvalButtons[1].noShow = false;
          } else {
            this.approvalButtons[1].noShow = true;
          }
        } else {
          this.$message({
            showClose: true,
            message: res.data.message,
            type: "error",
            ccuiCustom: true,
            duration: 8000,
          });
        }

        // this.approvalButtonAuth = {
        //   btnDisAgree: "1",
        //   btnBack: "1",
        //   btnEdit: "1",
        //   bizState: 1,
        //   btnTell: "1",
        //   btnAssist: "1",
        //   btnTransfer: "1",
        //   btnAgree: "1",
        //   btnResubmit: "1"
        // };
      });
    },
    // 返回
    handleBack() {
      this.$router.back();
    },
    // 同意,不同意底部按钮点击
    dialogAgreeClick(type) {
      this.dialogAgreeValue = type === "agree" ? "同意" : "";
      this.dialogAgree = true;
      this.dialogAgreeType = type;
    },
    // 转审,协办底部按钮点击
    dialogTransferClick(type) {
      this.dialogTransfer = true;
      this.dialogTransferType = type;
    },
    // 转审,协办人员加载
    dialogTransferLoadNode(node, resolve) {
      if (node) {
        let obj = {
          transfer: 6,
          assist: 5,
          notify: 7,
        };
        if (node.level === 0) {
          let parentIdArr = this.autoCode.split("-");
          parentIdArr.pop();
          parentIdArr.pop();
          getPartyRelationTree({
            thisPartyId: null,
            currentOperUserId: this.businessParams.currentOperUserId,
            currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
            agentId: this.businessParams.agentId,
            queryTypeCode: obj[this.dialogTransferType],
            isShowLoading: true,
            loadingMessage: "加载中,请稍等...",
          })
            .then((res) => {
              // debugger
              // this.dataKeys = res.data.data;
              this.expandedKeys = [];
              this.expandedKeys = parentIdArr.map((item) => Number(item));
              resolve(res.data.data);
            })
            .catch((e) => {
              resolve([]);
            });
        }
        if (node.level > 0) {
          // debugger
          getPartyRelationTree({
            thisPartyId: node.data.partyId,
            currentOperUserId: this.businessParams.currentOperUserId,
            currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
            agentId: this.businessParams.agentId,
            queryTypeCode: obj[this.dialogTransferType],
            isShowLoading: true,
            loadingMessage: "加载中,请稍等...",
          })
            .then((res) => {
              this.$refs.tree.setCurrentKey(
                this.expandedKeys[this.expandedKeys.length - 1]
              );
              resolve(res.data.data);
            })
            .catch((e) => {
              resolve([]);
            });
        }
      }
    },
    // 点击弹窗取消按钮
    handleEsc() {
      this.dialogTransfer = false;
      this.dialogTag = "";
    },
    // 转审,协办人员点击
    dialogTransferNodeClick(item) {
      if (this.dialogTransferType == "notify") {
        !this.dialogTransferTags.find((value) => {
          return item.id === value.id;
        }) &&
          item.userId &&
          this.dialogTransferTags.push(item) &&
          this.dialogTag.push(item.id);
      } else {
        !this.dialogTransferTags.find((value) => {
          return item.id === value.id;
        }) &&
          item.userId &&
          this.dialogTransferTags.length < 1 &&
          this.dialogTransferTags.push(item) &&
          this.dialogTag.push(item.id);
      }
    },
    // 转审,协办删除人员
    dialogTransferTagsClose(tag) {
      this.dialogTransferTags.splice(this.dialogTransferTags.indexOf(tag), 1);
    },
    // 转审,协办清空数据
    dialogTransferClose() {
      this.dialogTransferTags = [];
      this.dialogTransferValue = "";
      this.dialogTag = [];
      this.dialogTransferReset = false;
      this.$nextTick(() => {
        this.dialogTransferReset = true;
      });
    },
    // 退回清空数据
    dialogReturnClose() {
      this.dialogReturnTags = [];
      this.dialogReturn = false;
    },
    // 退回底部按钮点击
    dialogReturnClick(selectTypeCode = "1") {
      this.dialogReturn = true;
      const obj = {
        procInstId: this.businessParams.procInstId,
        actInstId: this.businessParams.actInstId,
        taskId: this.businessParams.workItemId,
        businessBillId: this.businessParams.businessBillId,
        businessCode: this.businessParams.businessCode,
        businessBillType: this.businessParams.businessBillTypeCode,
        // orgId: this.orgId,
        // appId: this.businessParams.appId,
        // agentId: this.businessParams.agentId,
        selectTypeCode,
        isShowLoading: true,
        loadingMessage: "加载中,请稍等...",
        currentOperUserId: this.businessParams.currentOperUserId,
        currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
      };
      // 延迟请求,loading不出现问题
      this.$nextTick(() => {
        getReturnPerson(obj).then((res) => {
          this.dialogReturnPerson = res.data.data;
          this.$nextTick(() => {
            this.dialogReturnPersonClick(this.dialogReturnPerson[0]);
          });
        });
      });
    },
    //退回选择审批人or上一环节审批人
    handleSelect(selectTypeCode) {
      this.dialogReturnClick(selectTypeCode);
    },
    // 退回人员点击
    dialogReturnPersonClick(item) {
      // !this.dialogReturnTags.find(value => {
      //   return item.id === value.id;
      // }) &&
      //   this.dialogReturnTags.length < 1 &&
      //   this.dialogReturnTags.push(item);
      this.dialogReturnTags = [item];
    },
    // 退回人员删除
    dialogReturnTagsClose(tag) {
      this.dialogReturnTags.splice(this.dialogReturnTags.indexOf(tag), 1);
    },
    // 所有dialog确定按钮点击
    dialogAgreeSubmit(type, verify) {
      if (!this.isRepeatedly) {
        this.isRepeatedly = true;
        let isVerify = false;
        verify &&
          verify.forEach((item) => {
            if (
              Object.prototype.toString.call(this[item]) === "[object Array]"
            ) {
              if (this[item].length === 0) {
                this.$message({
                  showClose: true,
                  message: "人员不能为空",
                  type: "error",
                  ccuiCustom: true,
                  duration: 8000,
                });
                isVerify = true;
                this.isRepeatedly = false;
              }
            } else {
              if (this[item].length > 500) {
                this.$message({
                  showClose: true,
                  message: "您输入超过500字，请重新输入",
                  type: "error",
                  ccuiCustom: true,
                  duration: 8000,
                });
                isVerify = true;
                this.isRepeatedly = false;
              }
            }
          });
        if (isVerify) {
          return;
        }
        if (type !== "notify") {
          this.getApprovalExecute(type);
        } else {
          this.notifyFn(type);
        }
      }
    },
    // 同意,不同意,退回,转审,协办 接口调用
    getApprovalExecute(type) {
      const typeObj = {
        // 同意
        agree: {
          operCode: 2,
          opinion: "dialogAgreeValue",
          dialogType: "dialogAgree",
          actionFn: postExecuteAgree,
        },
        // 不同意
        disAgree: {
          operCode: 4,
          opinion: "dialogAgreeValue",
          dialogType: "dialogAgree",
          actionFn: postExecuteDisagree,
        },
        resubmit: {
          operCode: 8,
          opinion: "dialogAgreeValue",
          dialogType: "dialogAgree",
        },
        // 退回
        returnPerson: {
          operCode: 3,
          opinion: "dialogReturnValue",
          participantList: "dialogReturnTags",
          dialogType: "dialogReturn",
          isApplyUser:
            this.dialogReturnTags.length > 0 &&
            (this.dialogReturnTags[0].activityDefID === "startActivity"
              ? 1
              : 0),
          participantListId: "id",
          actionFn: postExecuteReturn,
        },
        // 转审
        transfer: {
          operCode: 6,
          opinion: "dialogTransferValue",
          participantList: "dialogTransferTags",
          dialogType: "dialogTransfer",
          participantListId: "userId",
          participantListDeptId: "deptId",
          //  queryTypeCode: 5
          actionFn: postExecuteTransfer,
        },
        // 协办
        assist: {
          operCode: 5,
          opinion: "dialogTransferValue",
          participantList: "dialogTransferTags",
          dialogType: "dialogTransfer",
          //  bizState: 3,
          participantListId: "userId",
          participantListDeptId: "deptId",
          //  queryTypeCode: 6
          actionFn: postExecuteAssist,
        },
      };
      if (['agree', 'returnPerson'].includes(type) && !this[typeObj[type].opinion]) {
        this.$showErrorMessage("审批意见为必填项！")
        this.isRepeatedly = false;
        return
      }
      const obj = {
        isShowLoading: true,
        loadingMessage: "审批中,请稍等...",
        bizState: this.approvalButtonAuth.bizState,
        procInstId: this.businessParams.procInstId,
        actInstId: this.businessParams.actInstId,
        actInstName: this.businessParams.actInstName,
        taskId: this.businessParams.workItemId,
        // taskName: this.businessParams.taskName,
        opinion: this[typeObj[type].opinion],
        // operCode: typeObj[type].operCode,
        businessBillId: this.businessParams.businessBillId,
        businessCode: this.businessParams.businessCode,
        businessBillType: this.businessParams.businessBillTypeCode,
        //   orgId: this.orgId,
        businessAppId: this.businessParams.businessAppId,
        businessOrgId: this.orgId,
        // agentId: this.businessParams.agentId,
        isApplyUser: typeObj[type].isApplyUser ? typeObj[type].isApplyUser : 0,
        isMultiWorkItem: Number(this.isMultiWorkItem),
        currentOperUserId: this.businessParams.currentOperUserId,
        currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
        approvalInterfacePath: "",
        // requestType: this.getRequestType(),
        // extendMap: {},
        participantList: typeObj[type].participantList
          ? this[typeObj[type].participantList].map((item) => {
            return {
              id:
                type === "returnPerson"
                  ? item[typeObj[type].participantListId]
                  : item[typeObj[type].participantListId] +
                  "#" +
                  item[typeObj[type].participantListDeptId],
              name: item.name,
              typeCode: item.typeCode || "emp",
              workItemID: item.workItemID || "",
              activityDefID: item.activityDefID || "",
              activityInstID:
                type === "returnPerson" ? item.activityInstID : "",
            };
          })
          : [],
        //   queryTypeCode: typeObj[type].queryTypeCode
      };
      typeObj[type]
        .actionFn(obj)
        .then((res) => {
          this.isRepeatedly = false;
          this.$message({
            showClose: true,
            message: res.data.message,
            ccuiCustom: true,
            type: "success",
            duration: 2000,
          });
          if (res.data.code == "0") {
            this.commonLock = false;
            // this.$router.push(this.breadcrumbObj.path);
            this.handleBack();
          } else {
            // this.getList();
          }
          this[typeObj[type].dialogType] = false;
          this.dialogReturnValue = "退回";
        })
        .catch((res) => {
          if (res.data.code === "1") {
            // window.location.reload();
            // this.getList();
          }
        });
    },
    handleChangeTag() {
      this.dialogTransferTags = this.dialogTransferTags.filter((item) => {
        return this.dialogTag.find((data) => {
          return item.id === data;
        });
      });
    },
    // 知会接口调用
    notifyFn(type) {
      // let params = {
      //   isShowLoading: true,
      //   loadingMessage: "审批中,请稍等...",
      //   title: this.businessParams.title,
      //   applyTime: this.businessParams.applyTime,
      //   applyUserId: this.businessParams.applyUserId,
      //   applyUserName: this.businessParams.applyUserName,
      //   applyDeptId: this.businessParams.applyDeptId,
      //   applyDeptName: this.businessParams.applyDeptName,
      //   applyUnitId: this.businessParams.applyUnitId,
      //   applyUnitName: this.businessParams.applyUnitName,
      //   procInstId: this.businessParams.procInstId,
      //   actInstId: this.businessParams.actInstId,
      //   actInstName: this.businessParams.actInstName,
      //   taskId: this.businessParams.taskId,
      //   participantType: this.businessParams.participantType,
      //   businessBillId: this.businessParams.businessBillId,
      //   businessCode: this.businessParams.businessCode,
      //   businessBillType: this.businessParams.businessBillType,
      //   agentId: this.businessParams.agentId,
      //   createUserId: this.businessParams.createUserId,
      //   createTime: this.businessParams.createTime,
      //   createAgentId: this.businessParams.createAgentId,
      //   businessAppId: this.businessParams.appId,
      //   isDelete: this.businessParams.isDelete,
      //   businessOrgId: this.orgId,
      //   isMultiWorkItem: Number(this.isMultiWorkItem),
      //   currentOperUserId: this.businessParams.currentOperUserId,
      //   currentOperUserDeptId: this.businessParams.currentOperUserDeptId,
      //   bizState: this.approvalButtonAuth.bizState,
      //   requestType: this.getRequestType(),
      //   extendMap: {},
      //   partyList: this.dialogTransferTags
      //     .filter(item => {
      //       return this.dialogTag.find(data => {
      //         return item.id === data;
      //       });
      //     })
      //     .map(item => {
      //       return {
      //         tenantId: item.tenantId,
      //         partyAutoCode: item.autoCode,
      //         parentPartyId: item.parentPartyId,
      //         partyId: item.partyId,
      //         code: item.code,
      //         name: item.name,
      //         // abbrName:item.abbrName,
      //         partyTypeCode: item.partyTypeCode,
      //         deptId: item.deptId,
      //         userId: item.userId
      //       };
      //     })
      // };
      // getReadMsgBatchAdd(params).then(res => {
      //   this.isRepeatedly = false;
      //   this.$message({
      //     showClose: true,
      //     message: res.data.message,
      //     ccuiCustom: true,
      //     type: "success",
      //     duration: 2000
      //   });
      //   if (res.data.code == "0") {
      //     // this.$router.push(this.breadcrumbObj.path);
      //     this.handleBack();
      //   }
      //   this.dialogTransfer = false;
      // });
    },
    // 打印
    handlePrint() {
      this.$nextTick(() => {
        // this.$refs.noPrintTop.innerHTML = "";
        // this.$refs.noPrintBottom.innerHTML = "";
        window.print();
        // location.reload();
      });
    },
    //  更新我的待阅中已阅按钮
    // getUpdataRead() {
    //   let obj = {
    //     id: this.businessParams.id,
    //     businessBillId: this.businessParams.businessBillId,
    //     businessCode: this.businessParams.businessCode,
    //     businessBillType: this.businessParams.businessBillType,
    //     businessAppId: this.businessParams.appId,
    //     businessOrgId: this.orgId,
    //     procInstId: this.businessParams.procInstId,
    //     actInstId: this.businessParams.actInstId,
    //     actInstName: this.businessParams.actInstName,
    //     taskId: this.businessParams.taskId,
    //     readOpinion: "",
    //     agentId: this.businessParams.agentId,
    //     currentOperUserId: this.businessParams.readUserId,
    //     currentOperUserDeptId: this.businessParams.readUserDeptId
    //   };
    //   getUpdataRead(obj).then(res => {
    //     this.$message({
    //       showClose: true,
    //       message: res.data.message,
    //       ccuiCustom: true,
    //       type: "success",
    //       duration: 2000
    //     });
    //     if (res.data.code == "0") {
    //       // this.$router.push(this.breadcrumbObj.path);
    //       this.handleBack();
    //     }
    //   });
    // },
    // 按钮切换
    tabBtnChange({ value }) {
      this.isFocus = value;
      this.$refs[value].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start", // 上边框与视窗顶部平齐。默认值
      });
    },
  },
  activated() {
    this.getApprovalButton();
    this.selectTypeCode = "1";
  }
};
